<?php

namespace app\api\controller;

use app\BaseController;
use app\api\model\UserModel;
use app\api\validate\UserValidate;
use think\facade\Db;
use think\facade\Request;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;

class User extends BaseController
{
    public function register()
    {
        // 获取请求数据
        $data = Request::post();

        // 验证数据
        $validate = new UserValidate();
        if (!$validate->check($data)) {
            return error($validate->getError());
        }

        // 检查手机号是否已存在
        if (UserModel::where('mobile', $data['mobile'])->find()) {
            return error('手机号已被注册');
        }

        // 验证短信验证码
        if (!checkSmsCode($data['mobile'], $data['code'])) {
            return error('验证码错误或已过期');
        }

        // 生成随机盐值
        $salt = createRandStr(8);

        // 密码加密使用 MD5 并加盐
        $data['password'] = md5($data['password'] . $salt);
        $data['salt'] = $salt;

        // 创建用户
        try {
            $user = UserModel::create($data);
            return success($user->toArray());
        } catch (\Exception $e) {
            return error($e->getMessage());
        }
    }

    public function login()
    {
        $data = Request::post();

        // 获取用户信息
        $user = UserModel::where('mobile', $data['mobile'])->find();
        if (!$user) {
            return error('账号不存在');
        }

        // 验证密码
        if (md5($data['password'] . $user['salt']) != $user['password']) {
            return error('密码错误');
        }

        // 生成 token
        $token = signToken($user->id, $user->mobile);
        return success(['token' => $token], '登录成功');
    }

    public function sendSms()
    {
        $mobile = Request::post('mobile');

        // 检查手机号是否已存在
        if (UserModel::where('mobile', $mobile)->find()) {
            return error('手机号已被注册');
        }

        // 生成验证码
        $code = mt_rand(1000, 9999);

        // 将验证码存储到数据库，有效期5分钟
        Db::name('sms_code_log')->insert([
            'mobile' => $mobile,
            'code' => $code,
            'send_time' => time()
        ]);

        // 发送短信
        $config = new Config([
            "accessKeyId" => config('app.aliSms.accessKeyId'),
            "accessKeySecret" => config('app.aliSms.accessKeySecret')
        ]);
        $config->endpoint = "dysmsapi.aliyuncs.com";
        $client = new Dysmsapi($config);

        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $mobile,
            "signName" => "阿里云短信测试",
            "templateCode" => "SMS_154950909",
            "templateParam" => json_encode(["code" => $code])
        ]);

        try {
            $client->sendSmsWithOptions($sendSmsRequest, new RuntimeOptions([]));
            return success([], '短信发送成功');
        } catch (\Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            return error($error->getMessage());
        }
    }
    private function deleteSmsCode($mobile)
    {
        Db::name('sms_code_log')->where('mobile', $mobile)->delete();
    }
}
